/**
 * Author:  Lgh.
 * Date:    2018/7/24.
 * File：   .
 */

/**
 * 深拷贝
 * @param {Object} 被复制的对象
 * @param {Object} 目标对象,默认为空对象
 * @return {Object}}
 */
function clone (obj, target) {
  target = target || {}
  for (var i in obj) {
    if (typeof obj[i] === 'object') {
      target[i] = (obj[i].constructor === Array) ? [] : {}
      exports.clone(obj[i], target[i])
    } else {
      target[i] = obj[i]
    }
  }
  return target
}
/**
 * 从数组中移除一个对象
 * @param arr 数组对象
 * @param field 移除的字段匹配
 * @param text 匹配的值
 * @return {Boolean}
 */
function arrayRemoveOne (arr, field, text) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][field] === text) {
      arr.splice(i, 1)
      return true
    }
  }
  return false
}

/**
 * 判断对象是否为空对象
 * @param e 判断对象
 * @returns {boolean}
 */
function isEmptyObject (e) {
  // vue 框架给数组添加了一个$remove的方法，所以对数组单独判断
  if (e instanceof Array) {
    if (e.length > 0) {
      return false
    } else {
      return true
    }
  }
  for (var t in e) {
    return false
  }
  return true
}

/**
 * 触发点击事件
 * @param element
 */
function clickElement (element) {
  // console.log('hello')
  // console.log(typeof  element)
  if (typeof element === 'string') {
    element = document.getElementById(element)
  }
  console.log(navigator.userAgent)
  var e = document.createEvent('MouseEvents')
  e.initEvent('click', true, true)
  element.dispatchEvent(e)
  if (exports.getDeviceType() === 'iPhone') {
    // ios需要再触发click才能生效
    element.click()
  }
}

/**
 * 锁定
 * @param element 要锁定的dom
 * @param timeOut 锁定时间，默认1秒
 * @return {boolean} 是否在锁定状态中
 */
function freeze (element, timeOut) {
  timeOut = timeOut || 1000
  if (typeof element === 'string') {
    element = document.getElementById(element)
  }
  let freezeFlag = element.getAttribute('freeze-flag') // 是否锁定中
  let freezeFlagCountdown = element.getAttribute('freeze-flag-countdown') // 是否已经开始倒计时解锁中
  if (freezeFlag) {
    if (!freezeFlagCountdown) {
      element.setAttribute('freeze-flag-countdown', 'true') // 开始倒计时
      setTimeout(() => { // 倒计时结束
        element.removeAttribute('freeze-flag-countdown')
        element.removeAttribute('freeze-flag')
      }, timeOut)
    }
    return true
  } else {
    element.setAttribute('freeze-flag', 'true')
    element.removeAttribute('freeze-flag-countdown')
    return false
  }
}
/**
 * 获取设备类型
 * @return string 'Android'or'iPhone or'Windows'or'unknown'
 */
function getDeviceType () {
  var agent = navigator.userAgent
  var device = ''
  if (agent.indexOf('Android') !== -1) {
    device = 'Android'
  } else if (agent.indexOf('iPhone') !== -1) {
    device = 'iPhone'
  } else if (agent.indexOf('Windows') !== -1) {
    device = 'Windows'
  } else {
    device = 'unknown'
  }
  return device
}
/**
 * 压缩图片
 * @param file 图片文件
 * @param fileSize 图片文件的大小
 * @callBack 压缩完成后的回调函数，参数：(base64)
 */
function compress (file, callBack) {
  var img = new window.Image()
  // 最大宽度
  var maxW = 640
  // 压缩比
  var compressRate = 0.6

  img.onload = function () {
    var cvs = document.createElement('canvas')
    var ctx = cvs.getContext('2d')

    if (img.width > maxW) {
      img.height *= maxW / img.width
      img.width = maxW
    }
    cvs.width = img.width
    cvs.height = img.height
    ctx.clearRect(0, 0, cvs.width, cvs.height)
    ctx.drawImage(img, 0, 0, img.width, img.height)

    var dataUrl = cvs.toDataURL('images/jpeg', compressRate)
    if (typeof callBack === 'function') {
      callBack(dataUrl)
    }
  }

  img.src = file
}
/**
 * 冷却，防止快速重复点击
 * @param element 要冷却的节点
 * @param coolingTime 冷却时间（ms），默认为1000(ms)
 */
function coolingElement (element, coolingTime) {
  coolingTime = coolingTime || 1000
  if (typeof element === 'string') {
    element = document.getElementById(element)
  }
  element.disabled = true
  setTimeout(function () {
    element.disabled = false
  }, coolingTime)
}

/**
 * 初始化百度地图对象
 * @param key 百度密钥
 * @returns {Promise} 异步对象
 */
function initMap (key) {
  return new Promise((resolve, reject) => {
    var script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = 'http://api.map.baidu.com/getscript?v=2.0&ak=' + key + '&services=&t=' + (new Date()).getTime()
    script.onload = (event) => {
      resolve(window.BMap, event)
    }
    script.onerror = (error) => {
      reject(error)
    }
    document.head.appendChild(script)
  })
}
/**
 * 直接获取定位对象
 * @returns {Promise}
 */
function getLocal () {
  return new Promise((resolve, reject) => {
    exports.initMap('tzAcIFZ5xCoRwm63NcBGfoVB').then(BMap => {
      var getLocation = new BMap.Geolocation()
      var geocoder = new BMap.Geocoder()
      getLocation.getCurrentPosition(function (cp) {
        geocoder.getLocation(cp.point, function (cl) {
          var options = cl.addressComponents
          options.point = cl.point
          resolve(options)
        })
      }, function (e) {
        console.log('getCurrentPosition失败：')
        console.log(e)
      })
    }, e => {
      console.log('initMap失败：')
      console.log(e)
    })
  })
}
/**
 * 字符串转bool
 * @param str
 * @returns {boolean}
 */
function strToBool (str) {
  if (typeof str === 'boolean') {
    return str
  } else if (typeof str === 'string') {
    return str === 'true'
  } else {
    return false
  }
}

function getNowFormatDate () {
  var date = new Date()
  var seperator1 = '-'
  var seperator2 = ':'
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var strDate = date.getDate()
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()

  if (month >= 1 && month <= 9) {
    month = '0' + month
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = '0' + strDate
  }
  if (hour >= 0 && hour <= 9) {
    hour = '0' + hour
  }
  if (minute >= 0 && minute <= 9) {
    minute = '0' + minute
  }
  if (second >= 0 && second <= 9) {
    second = '0' + second
  }
  var currentdate = year + seperator1 + month + seperator1 + strDate + ' ' + hour + seperator2 + minute + seperator2 + second
  return currentdate
}

/**
 * 计算时间差
 * @param time1 开始时间
 * @param time2 结束时间
 * @returns {{days: number, hours: number, minutes: number, seconds: number}}
 */
function timeDif (time1, time2) {
  if (!(time1 instanceof Date)) {
    time1 = time1.replace(/-/g, function () { // ios 2017-01-01 格式无法做为new Date()的参数，需改为2017/01/02
      return '/'
    })
    time1 = new Date(time1)
  }
  if (!(time2 instanceof Date)) {
    time2 = time2.replace(/-/g, function () { // ios 2017-01-01 格式无法做为new Date()的参数，需改为2017/01/02
      return '/'
    })
    time2 = new Date(time2)
  }
  var dif = time2.getTime() - time1.getTime() // 时间差的毫秒数
  // 计算出相差天数
  var days = Math.floor(dif / (24 * 3600 * 1000))
  // 计算出小时数
  var leave1 = dif % (24 * 3600 * 1000) // 计算天数后剩余的毫秒数
  var hours = Math.floor(leave1 / (3600 * 1000))
  // 计算相差分钟数
  var leave2 = leave1 % (3600 * 1000) // 计算小时数后剩余的毫秒数
  var minutes = Math.floor(leave2 / (60 * 1000))
  // 计算相差秒数
  var leave3 = leave2 % (60 * 1000) // 计算分钟数后剩余的毫秒数
  var seconds = Math.round(leave3 / 1000)
  return {days: days, hours: hours, minutes: minutes, seconds: seconds}
}

// 'yyyy-MM-dd hh:mm:ss
function formatDate (dateObj, format = 'yyyy-MM-dd hh:mm:ss') {
  var date = {
    'M+': dateObj.getMonth() + 1,
    'd+': dateObj.getDate(),
    'h+': dateObj.getHours(),
    'm+': dateObj.getMinutes(),
    's+': dateObj.getSeconds(),
    'q+': Math.floor((dateObj.getMonth() + 3) / 3),
    'S+': dateObj.getMilliseconds()
  }
  if (/(y+)/i.test(format)) {
    format = format.replace(RegExp.$1, (dateObj.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (var k in date) {
    if (new RegExp('(' + k + ')').test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length === 1
        ? date[k] : ('00' + date[k]).substr(('' + date[k]).length))
    }
  }
  return format
}

// 时间戳转为时间 yyyy-MM-dd hh:mm:ss
function timestampToDate (value, format) {
  format = format || 'yyyy-MM-dd hh:mm:ss'
  var date = new Date()
  date.setTime(value * 1000)
  var dateStr = formatDate(date, format)
  return dateStr
}

function getQueryString (name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
  var r = window.location.search.substr(1).match(reg)
  if (r != null) {
    return unescape(r[2])
  }
  return null
}

/***
 * 节流函数 连续调用不会一直触发，只有在等待wait时间后再次调用才会再触发一次
 * @param func 执行函数
 * @param wait 等待时间
 * @param immediate 是否立即执行
 * @return {Function}
 */
function throttle (func, wait, immediate) {
  var timeout
  return function () {
    let context = this
    let args = arguments
    let later = function () {
      timeout = null
      if (!immediate) func.apply(context, args)
    }
    let callNow = immediate && !timeout
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
    if (callNow) func.apply(context, args)
  }
}
/***
 * 节流函数2 连续调用，在每等待wait时间后就触发一次
 * @param func 执行函数
 * @param wait 等待时间
 * @param immediate 是否立即执行
 * @return {Function}
 */
function throttle2 (func, wait, immediate) {
  var timeout
  return function () {
    let context = this
    let args = arguments
    let later = function () {
      timeout = null
      if (!immediate) func.apply(context, args)
    }
    let callNow = immediate && !timeout
    if (!timeout) {
      timeout = setTimeout(later, wait)
    }
    if (callNow) func.apply(context, args)
  }
}
function HTMLDecode (text) {
  var temp = document.createElement('div')
  temp.innerHTML = text || ''
  var output = temp.innerText || temp.textContent
  temp = null
  return output
}
/***
 * 设置cookie
 * @param c_name 键名
 * @param value  键值
 * @param expiredays 过期时间(天)
 */
function setCookie (cName, value, expiredays) {
  var exdate = new Date()
  exdate.setDate(exdate.getDate() + expiredays)
  document.cookie = cName + '=' + escape(value) + ((expiredays == null) ? '' : ';expires=' + exdate.toGMTString())
}

/***
 * 读取cookie
 * @param c_name 键名
 * @returns {string}
 */
function getCookie (cName) {
  if (document.cookie.length > 0) {
    let cStart = document.cookie.indexOf(cName + '=')
    if (cStart !== -1) {
      cStart = cStart + cName.length + 1
      let cEnd = document.cookie.indexOf(';', cStart)
      if (cEnd === -1) cEnd = document.cookie.length
      return unescape(document.cookie.substring(cStart, cEnd))
    }
  }
  return ''
}

/**
 * 对象转化
 * @param vueObject
 * @returns {*}
 */
function restore (vueObject) {
  var result = null
  var type = Object.prototype.toString.call(vueObject)
  switch (type) {
    case '[object Array]':
      result = toArray(vueObject)
      break
    case '[object Object]':
      result = toObject(vueObject)
      break
    default:
      result = vueObject
      break
  }
  function toArray (vueArray) {
    var array = []
    for (var index in vueArray) {
      var item = restore(vueArray[index])
      array.push(item)
    }
    return array
  }
  function toObject (vueObject) {
    var obj = new Object()
    for (var index in vueObject) {
      var item = restore(vueObject[index])
      obj[index] = item
    }
    return obj
  }
  return result
}

export {
  clone,
  arrayRemoveOne,
  isEmptyObject,
  clickElement,
  freeze,
  getDeviceType,
  compress,
  coolingElement,
  initMap,
  getLocal,
  strToBool,
  getNowFormatDate,
  timeDif,
  formatDate,
  timestampToDate,
  getQueryString,
  throttle,
  throttle2,
  HTMLDecode,
  setCookie,
  getCookie,
  restore
}
